package org.jeecg.modules.websocket.handler;

import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.exception.JeecgBoot401Exception;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.modules.iot.api.IControlAPI;
import org.jeecg.modules.websocket.manager.WebSocketSessionManager;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.time.LocalDateTime;

/**
 * @author by sean
 * @desc:
 * @since 2024-10-16 星期三 11:23:23
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class WebSocketHandler extends TextWebSocketHandler {

    private final IControlAPI controlApi;

    /**
     * 建立成功事件
     * @param session
     * @throws Exception
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String terminalCode = (String) session.getAttributes().get("terminalCode");
        String token = (String) session.getAttributes().get("token");
        String type = (String) session.getAttributes().get("type");
        if (StrUtil.isNotBlank(token) && StrUtil.isNotBlank(type)) {
            //TODO 后续可以验证token是否有效
            // 用户连接成功，放入在线用户缓存
            String username = JwtUtil.getUsername(token);
            WebSocketSessionManager.addSession(terminalCode, username, session);
            //TODO 推送一次
            try{
                controlApi.pushEBikeInfo(terminalCode);
            }catch (Exception e){
//                e.printStackTrace();
                log.error("连上WebSocket,发起推送请求，出现异常{}", e.getMessage());
            }
        } else {
            throw new JeecgBoot401Exception("用户登录已经失效!");
        }
        super.afterConnectionEstablished(session);
    }

    /**
     * 文本消息事件
     * @param session
     * @param message
     * @throws Exception
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 获得客户端传来的消息
        String payload = message.getPayload();
        Object token = session.getAttributes().get("token");
        log.debug("server 接收到 {} 发送的 {}", token, payload);
        String msg = "server 发送给 " + token + " 消息 " + payload + " " + LocalDateTime.now().toString();
//        session.sendMessage(new TextMessage("server 发送给 " + token + " 消息 " + payload + " " + LocalDateTime.now().toString()));
        super.handleTextMessage(session, message);
    }

    /**
     * 断开连接
     * @param session
     * @param status
     * @throws Exception
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        Object token = session.getAttributes().get("token");
        Object terminalCode = session.getAttributes().get("terminalCode");
        if (token != null) {
            // 用户退出，移除缓存
            WebSocketSessionManager.removeSession(terminalCode.toString(), token.toString());
        }
        super.afterConnectionClosed(session, status);
    }
}
